package org.platform.lwc.redis.factory.lettuce;

import cn.hutool.core.util.ObjectUtil;
import io.lettuce.core.RedisURI;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

import java.time.Duration;

/**
 * @Description: 获取 LettuceConnectionFactory 接口
 * @Author: lwc
 * @Date: 2021/5/20
 *
 *
 * ClusterTopologyRefreshOptions配置用于开启自适应刷新和定时刷新。如自适应刷新不开启，
 * Redis集群变更时将会导致连接异常！ (+++++++++++++++++++++这里暂时不处理+++++++++++++++++++++)
 */
public interface ObtainLettuceConnection {

    LettuceConnectionFactory obtainLettuceConnection(RedisProperties redisProperties);

    default LettucePoolingClientConfiguration getLettucePoolingClientConfiguration(RedisProperties redisProperties){
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        RedisProperties.Pool pool = redisProperties.getLettuce().getPool();
           genericObjectPoolConfig.setMaxIdle(pool.getMaxIdle());
        genericObjectPoolConfig.setMinIdle(pool.getMinIdle());
        genericObjectPoolConfig.setMaxTotal(pool.getMaxActive());
        genericObjectPoolConfig.setMaxWaitMillis(pool.getMaxWait().toMillis());
        Duration shutdownTimeout = redisProperties.getLettuce().getShutdownTimeout();
        LettucePoolingClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder()
                .commandTimeout(ObjectUtil.isNotNull(redisProperties.getTimeout())?redisProperties.getTimeout(): Duration.ofSeconds(RedisURI.DEFAULT_TIMEOUT))
                .poolConfig(genericObjectPoolConfig)
                .build();
        return lettuceClientConfiguration;
    }
}
